//
//  ADRequest.m
//  iCarStyle
//
//  Created by liunian on 13-9-6.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "ADRequest.h"
#import "HttpRequest.h"

#define apiSource @"http://imitao.sinaapp.com/api/icar_cover/list/"
@interface ADRequest ()
@property (nonatomic , assign) id<ReqDelegate>delegate;
@end
@implementation ADRequest
- (void)requestADWithDelegate:(id<ReqDelegate>)delegate;{
    _delegate = nil;
    _delegate = delegate;
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithCapacity:0];
    SET_PARAM(@"50", @"count", param);
    SET_PARAM(@"asc", @"ord", param);
    SET_PARAM(@"index", @"by", param);

    [[HttpRequest sharedClient] GET:apiSource parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
        NSMutableArray *rstArray = [NSMutableArray arrayWithCapacity:0];
        NSArray *sources = [[responseObject objectForKey:@"data"] objectForKey:@"items"];

        if (isArrayWithCountMoreThan0(sources)) {
            for (NSDictionary *dic in sources) {
                if (isDictWithCountMoreThan0(dic)) {
                    AdItem *s = [AdItem createWithDict:dic];
                    [rstArray addObject:s];
                }
            }

            if ([_delegate respondsToSelector:@selector(finishADReq:ads:)]) {
                [_delegate finishADReq:self ads:rstArray];
            }


        }else{
            if ([_delegate respondsToSelector:@selector(finishErrorReq:errorCode:message:)]) {
                [_delegate finishErrorReq:self errorCode:1 message:@"无数据"];
            }
        }

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if ([_delegate respondsToSelector:@selector(finishErrorReq:errorCode:message:)]) {
            [_delegate finishErrorReq:self errorCode:1 message:@"无数据"];
        }
    }];
}
@end
